package con.lagou.Intercetpor;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.compress.utils.Charsets;
import org.apache.commons.lang3.CharSet;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.event.SimpleEvent;
import org.apache.flume.interceptor.Interceptor;
import org.junit.Test;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: yehw
 * @date: 2020/8/29 23:21
 * @description: 自定义拦截器
 */
public class LogInterceptor implements Interceptor {
    @Override
    public void initialize() {

    }

    /**
     * @author:yehw
     * @date: 2020/8/29:23:25
     * @paramType:
     * @returnType:
     * @description: 核心处理方法
     */
    @Override
    public Event intercept(Event event) {
        //获得body
        byte[] body = event.getBody();
        String bodyStr = new String(body, Charsets.UTF_8);
        //获得header
        Map<String, String> headers = event.getHeaders();
        //解析body中的字符串
        String[] split = bodyStr.split("\\s+");
        try {
            String s = split[6];
            //定义最终时间戳
            String timeStr = "";
            JSONObject jsonObject = JSON.parseObject(s);
            if (headers.getOrDefault("logtype", "").equals("start")) {
                //启动日志时间戳
                timeStr = jsonObject.getJSONObject("app_active").getString("time");
            } else if (headers.getOrDefault("logtype", "").equals("event")) {
                //取事件日志第一条时间戳
                JSONArray lagou_event = jsonObject.getJSONArray("lagou_event");
                if (lagou_event.size() > 0) {
                    timeStr = lagou_event.getJSONObject(0).getString("time");
                }
            }
            //格式化时间戳
            long parseLong = Long.parseLong(timeStr);
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            Instant instant = Instant.ofEpochMilli(parseLong);
            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
            String format = dateTimeFormatter.format(localDateTime);
            //存放时间
            headers.put("logtime", format);
            event.setHeaders(headers);
        } catch (Exception e) {
            headers.put("logtime", "未知时间");
            event.setHeaders(headers);
        }
        return event;
    }

    /**
     * 多事件处理
     **/
    @Override
    public List<Event> intercept(List<Event> list) {
        //定义返回结果
        List<Event> out = new ArrayList<Event>();
        for (Event event : list) {
            Event intercept = intercept(event);
            if (intercept != null) {
                out.add(intercept);
            }
        }
        return out;
    }

    @Override
    public void close() {

    }

    public static class Builder implements Interceptor.Builder {

        @Override
        public Interceptor build() {
            return new LogInterceptor();
        }

        @Override
        public void configure(Context context) {

        }
    }

    @Test
    public void testStart() {
        // new Event
        Event event = new SimpleEvent();
        String str = "2020-08-20 11:56:08.211 [main] INFO  com.lagou.ecommerce.AppStart - {\"app_active\":{\"name\":\"app_active\",\"json\":{\"entry\":\"2\",\"action\":\"0\",\"error_code\":\"0\"},\"time\":1595288248066},\"attr\":{\"area\":\"三门峡\",\"uid\":\"2F10092A1\",\"app_v\":\"1.1.0\",\"event_type\":\"common\",\"device_id\":\"1FB872-9A1001\",\"os_type\":\"0.97\",\"channel\":\"WM\",\"language\":\"chinese\",\"brand\":\"xiaomi-3\"}}";
        Map<String, String> map = new HashMap<String, String>();
        map.put("logtype", "start");
        event.setHeaders(map);
        event.setBody(str.getBytes(Charsets.UTF_8));
        // 调用interceptor处理event
        LogInterceptor customerInterceptor = new LogInterceptor();
        Event outEvent = customerInterceptor.intercept(event);
        // 处理结果
        Map<String, String> headersMap = outEvent.getHeaders();
        System.out.println(JSON.toJSONString(headersMap));
    }
    /**
    * @author:yehw
    * @date: 2020/8/29:23:50
    * @paramType:
    * @returnType:
    * @description:  测试event日志
    */
    @Test
    public void testEvent() {
        Event event = new SimpleEvent();
        String str ="2020-08-20 12:00:58.395 [main] INFO  com.lagou.ecommerce.AppEvent - {\"lagou_event\":[{\"name\":\"goods_detail_loading\",\"json\":{\"entry\":\"2\",\"goodsid\":\"0\",\"loading_time\":\"92\",\"action\":\"3\",\"staytime\":\"10\",\"showtype\":\"0\"},\"time\":1595265099584},{\"name\":\"notification\",\"json\":{\"action\":\"1\",\"type\":\"3\"},\"time\":1595341087663},{\"name\":\"ad\",\"json\":{\"duration\":\"10\",\"ad_action\":\"0\",\"shop_id\":\"23\",\"event_type\":\"ad\",\"ad_type\":\"1\",\"show_style\":\"0\",\"product_id\":\"36\",\"place\":\"placecampaign2_left\",\"sort\":\"1\"},\"time\":1595276738208}],\"attr\":{\"area\":\"东莞\",\"uid\":\"2F10092A0\",\"app_v\":\"1.1.0\",\"event_type\":\"common\",\"device_id\":\"1FB872-9A1000\",\"os_type\":\"1.1\",\"channel\":\"AD\",\"language\":\"chinese\",\"brand\":\"iphone-0\"}}";
        Map<String, String> map = new HashMap<>();
        map.put("logtype", "event");
        event.setHeaders(map);
        event.setBody(str.getBytes(Charsets.UTF_8));
        // 调用interceptor处理event
        LogInterceptor customerInterceptor = new LogInterceptor();
        Event outEvent = customerInterceptor.intercept(event);
        // 处理结果
        Map<String, String> headersMap = outEvent.getHeaders();
        System.out.println(JSON.toJSONString(headersMap));
    }
}
